using System.Diagnostics;
using WeatherSystem.API.Configurations;

namespace WeatherSystem.API.Middleware
{
    /// <summary>
    /// 业务指标收集中间件
    /// </summary>
    public class MetricsMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IBusinessMetricsService _metricsService;
        private readonly ILogger<MetricsMiddleware> _logger;

        public MetricsMiddleware(
            RequestDelegate next,
            IBusinessMetricsService metricsService,
            ILogger<MetricsMiddleware> logger)
        {
            _next = next;
            _metricsService = metricsService;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var sw = Stopwatch.StartNew();
            var path = context.Request.Path.ToString();
            var method = context.Request.Method;

            try
            {
                await _next(context);
            }
            finally
            {
                sw.Stop();
                
                // 记录API请求指标
                var statusCode = context.Response.StatusCode;
                var durationMs = sw.Elapsed.TotalMilliseconds;
                
                // 简化路径用于指标分组（移除参数）
                var route = SimplifyRoute(path);
                
                _metricsService.RecordApiRequest(route, method, durationMs, statusCode);
                
                // 记录慢请求
                if (durationMs > 1000) // 超过1秒的请求
                {
                    _logger.LogWarning("慢请求检测: {Method} {Path} 耗时 {Duration}ms, 状态码: {StatusCode}",
                        method, path, durationMs, statusCode);
                }
            }
        }

        private static string SimplifyRoute(string path)
        {
            // 将带参数的路径简化为模板形式
            var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
            
            for (int i = 0; i < segments.Length; i++)
            {
                // 检查是否为GUID
                if (Guid.TryParse(segments[i], out _))
                {
                    segments[i] = "{id}";
                }
                // 检查是否为数字ID
                else if (int.TryParse(segments[i], out _))
                {
                    segments[i] = "{id}";
                }
            }
            
            return "/" + string.Join("/", segments);
        }
    }

    /// <summary>
    /// 性能追踪属性
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class TrackPerformanceAttribute : Attribute
    {
        public string? OperationName { get; set; }
        public bool TrackParameters { get; set; } = false;
        
        public TrackPerformanceAttribute(string? operationName = null)
        {
            OperationName = operationName;
        }
    }

    /// <summary>
    /// OpenTelemetry中间件扩展
    /// </summary>
    public static class OpenTelemetryMiddlewareExtensions
    {
        public static IApplicationBuilder UseMetricsMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MetricsMiddleware>();
        }
    }
}